#import <stdio.h>
#import <stdlib.h>
#import <strings.h>
#import <defaults.h>
#import <sys/types.h>
#import <sys/dir.h>
#import <sys/param.h>
#import <objc/objc-load.h>
#import <appkit/Application.h>
#import "ControlLoader.h"

@implementation ControlLoader

	id			controlObject;

- (char *)getImageControlFromPath: (char *)path ofType: (const char *)type
{
	DIR			*myDir;
	struct direct	*myEntry;
	static char	buffer[MAXPATHLEN];
	char			typeBuffer[MAXPATHLEN];
	
	sprintf(typeBuffer, "%s.controls", type);
	fprintf(stderr, "Opening %s to find %s\n", path, typeBuffer);
	myDir = opendir(path);
	if (myDir) {
		while (myEntry = readdir(myDir)) {
			if (!strcmp(myEntry->d_name, typeBuffer)) {
				strcpy(buffer, path);
				strcat(buffer, myEntry->d_name);
				fprintf(stderr, "Found image tools: %s\n", buffer);
				break;
			}
		}
		closedir(myDir);
	}
	else {
		fprintf(stderr, "Unable to open dir\n");
		return NULL;
	}

	return buffer;
}

- (char *)getImageControlsOfType: (const char *)type
{
	char		buffer[1000];
	char		*imagePath = NULL;
	char		*tmpPath;
	
	if (tmpPath=[self getImageControlFromPath: "/NextLibrary/Converters/" ofType: type]) {
		imagePath = tmpPath;
	}
	if (tmpPath=[self getImageControlFromPath: "/LocalLibrary/Converters/" ofType: type]) {
		imagePath = tmpPath;
	}
	sprintf(buffer, "%s/Library/Converters/", NXHomeDirectory());
	if (tmpPath = [self getImageControlFromPath: buffer ofType: type]) {
		imagePath = tmpPath;
	}

	return imagePath;
}

void LinkImageControlsCallBack(Class cl, Category ca)
{
	fprintf(stderr, "Call back for control object reached\n");
	controlObject = (id)cl;
	fprintf(stderr, "Linked object at %p\n", cl);
}

+ loadControl: (const char *)type
{
	NXStream	*myStream;
	char			*cvtFiles[] = {	NULL,
								"/usr/lib/libcs.a",
								"/usr/lib/libm.a", 
								"/usr/lib/libNeXT_s.a",
								"/lib/libsys_s.a",
								NULL };
	
	self = [super new];

	cvtFiles[0] = [self getImageControlsOfType: type];
	if (!cvtFiles[0]) {
		fprintf(stderr, "Fatal Error, unable to open controls type: %s\n", type);
		[self free];
		return nil;
	}
	myStream = NXOpenFile(fileno(stderr), NX_WRITEONLY);
	fprintf(stderr, "stderr linked to stream myStream\n");
	if (objc_loadModules(cvtFiles, myStream, LinkImageControlsCallBack, NULL, NULL)) {
		NXFlush(myStream);
		return nil;
	}
	NXFlush(myStream);
	NXClose(myStream);

	[self free];
	
	return controlObject;
}

@end
